package database

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/clickhouse"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

func InitDB() *gorm.DB {
	var err error

	host := viper.GetString("clickhouse.host")
	port := viper.GetString("clickhouse.port")
	database := viper.GetString("clickhouse.database")
	username := viper.GetString("clickhouse.username")
	password := viper.GetString("clickhouse.password")

	dsn := fmt.Sprintf("tcp://%s:%s?database=%s&username=%s&password=%s&read_timeout=10&write_timeout=20",
		host,
		port,
		database,
		username,
		password)

	gormConfig := gorm.Config{}
	if viper.GetString("server.mode") == "debug" {
		gormConfig.Logger = logger.Default.LogMode(logger.Info)
	}
	DB, err = gorm.Open(clickhouse.Open(dsn), &gormConfig)

	if err != nil {
		fmt.Printf("clickhouse connect error %v", err)
	}

	if DB.Error != nil {
		fmt.Printf("database error %v", DB.Error)
	}

	return DB
}
